from django.views.generic import View
from ..models import CaseSetModel, CaseSetDetailModel, CaseModel
from ..forms import CaseSetForm
from utils.messages import Json_Response, Form_Invalid
from utils.decorators import permission_verify
from utils.paginate import paginate
from utils.record import record
from utils.fmt import datetime_str
from copy import deepcopy


class CaseSetView(View):

    @permission_verify(40004)
    def create(self, request):
        form = CaseSetForm.Create(request)
        if form.is_valid():
            data = form.cleaned_data
            if CaseSetModel.objects.filter(name=data['name']):
                return Json_Response(code=201, err_msg='已经存在')
            obj = CaseSetModel.objects.create(**data)
            record(request, 11, obj)
            return Json_Response(msg='创建成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40004)
    def update(self, request):
        form = CaseSetForm.Update(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            qs = CaseSetModel.objects.filter(id=id)
            qs.update(**data)
            for obj in qs:
                obj.save()
                record(request,13, obj)
            return Json_Response(msg='修改成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40004)
    def delete(self, request):
        form = CaseSetForm.Delete(request)
        if form.is_valid():
            id = form.cleaned_data['id']
            for obj in CaseSetModel.objects.filter(id=id):
                obj_copy = deepcopy(obj)
                obj.delete()
                record(request, 12, obj_copy)
            return Json_Response(msg='删除成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40003)
    def list(self, request):
        form = CaseSetForm.List(request)
        if form.is_valid():
            result = []
            data = form.cleaned_data
            page, page_size = data.pop('page'), data.pop('page_size')
            qs = CaseSetModel.objects.filter()
            total = qs.count()
            for obj in paginate(qs, page, page_size).values_list(
                    'id', 'name', 'project__id', 'project__proj_name',
                    'create_by__id', 'create_by__usr_name',
                    'execute_num', 'execute_fin_time',
                    named=True
            ):
                result.append({
                    'id': obj.id,
                    'name': obj.name,
                    'project': {
                        'id': obj.project__id,
                        'name': obj.project__proj_name
                    },
                    'create_user': {
                        'id': obj.create_by__id,
                        'name': obj.create_by__usr_name
                    },
                    'execute_num': obj.execute_num,
                    'execute_fin_time': datetime_str(obj.execute_fin_time)
                })
            return Json_Response(msg='查询成功', data={
                'page': page,
                'page_size': page_size,
                'total': total,
                'result': result
            })
        else:
            return Form_Invalid(form)

    @permission_verify(40004)
    def register(self, request):
        form = CaseSetForm.Register(request)
        if form.is_valid():
            data = form.cleaned_data
            cases_obj, set_obj = data['cases_obj'], data['set_obj']
            # 清空
            for obj in CaseSetDetailModel.objects.filter(set=set_obj):
                obj.delete()
            for c_obj in cases_obj:
                CaseSetDetailModel.objects.create(**{
                    'set': set_obj,
                    'case': c_obj
                })
            return Json_Response(msg='修改成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40003)
    def cases_with_current_set(self, request):
        form = CaseSetForm.CurrentSetCases(request)
        if form.is_valid():
            data = form.cleaned_data
            set_id = data.pop('id')
            args = ['id', 'name', 'protocol', 'method', 'project__proj_name', 'url']

            result = []
            current_qs = CaseModel.objects.filter(to_case__set__id=set_id).values_list(*args, named=True)

            for obj in CaseModel.objects.filter().values_list(*args, named=True):
                result.append({
                    'id': obj.id,
                    'name': obj.name,
                    'method': obj.method,
                    'protocol': obj.protocol,
                    'project': obj.project__proj_name,
                    'url': obj.url,
                    'register': True if obj in current_qs else False
                })
            return Json_Response(msg='查询成功', data=result)
        else:
            return Form_Invalid(form)
